package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessQandA;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.AnswerVO;
import com.digitalchina.lxnsy.entity.TechnologyVO;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.AnswerListHolder;
import com.digitalchina.lxnsy.xml.UserXML;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.digitalchina.lxnsy.activity.old.AnswerQuestionActivity.RESULT_ANSWER_QUESTION_CODE;


/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/21 9:49
 * 修改备注：
 * ================================================
 */
public class AnswerListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;


    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;

    private TechnologyVO technologyVO;
    private View view;
    // headView 控件
    private TextView tvTitle;
    private TextView tvContent;
    private TextView tvDelete;
    private TextView tvAmend;
    private TextView tvToHtml;  // 点击查看html详情
    private TextView tvNumber;
    private LinearLayout linearLayout;


    private List<AnswerVO> answerVOList = new ArrayList<>();
    private String questionId = "";

    private static final int REQUEST_CODE_ASK_LIST = 0x1; // request code

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_answer_list);
        setTitle("回答列表");
    }

    @Override
    public void initMember() {

        technologyVO = (TechnologyVO) getIntent().getSerializableExtra("TechnologyVO");

        if (null == technologyVO.getQuestion()) {
            recyclerView.showEmpty();
            return;
        }

        initHeadView();

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapter(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new AnswerListHolder(parent);
            }
        });


        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                return view;
            }

            @Override
            public void onBindView(View headerView) {

            }
        });

        onRefresh();

    }

    /**
     * 初始化头部
     */
    private void initHeadView() {
        view = LayoutInflater.from(AnswerListActivity.this).inflate(R.layout.view_headview_answer_detail, null);
        tvTitle = (TextView) view.findViewById(R.id.answer_detail_tv_title);
        tvContent = (TextView) view.findViewById(R.id.answer_detail_tv_content);
        tvDelete = (TextView) view.findViewById(R.id.answer_detail_tv_delete);
        tvAmend = (TextView) view.findViewById(R.id.answer_detail_tv_amend);
        tvToHtml = (TextView) view.findViewById(R.id.answer_detail_tv_to_html);
        tvNumber = (TextView) view.findViewById(R.id.answer_detail_tv_number);
        linearLayout = (LinearLayout) view.findViewById(R.id.answer_detail_ll_write);

        if (technologyVO == null) {
            showToast("获取信息异常");
            return;
        }


        questionId = technologyVO.getQuestion().getId();

        tvTitle.setText(technologyVO.getQuestion().getTitle());
        tvContent.setText(StringUtil.html2Text(technologyVO.getQuestion().getWordContent()));
        tvNumber.setText(MessageFormat.format("{0}个回答", technologyVO.getQuestion().getAnswerCount()));

        // 删除问题
        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(AnswerListActivity.this)
                        .title("提示")
                        .content("确定要删除该问题吗？")
                        .negativeText("取消")
                        .positiveText("确定")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                BusinessQandA.deleteQuestion(AnswerListActivity.this, questionId, mHandler);
                            }
                        })
                        .show();
            }
        });

        // 问题详情
        tvToHtml.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isStrEmpty(questionId))
                    showToast("无法获取问题详情");
                else
                    GotoUtil.gotoActivity(AnswerListActivity.this, QuestionDetailActivity.class, "questionId", questionId);
            }
        });
        // 修改问题
        tvAmend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomDialog.nativeDialog(AnswerListActivity.this, "移动端暂时无法修改，请登录PC网页版操作！");
            }
        });

        // 回答问题
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isStrEmpty(questionId))
                    showToast("无法回答问题, 请检查网络, 刷新后尝试");
                else
                    GotoUtil.gotoForResultActivity(AnswerListActivity.this, AnswerQuestionActivity.class, REQUEST_CODE_ASK_LIST, "questionId", questionId);
            }
        });

        // 判断该问题是不是当前登录帐号发布的 如果是则显示修改按钮
        if (technologyVO.getPerson().getUserAccId().equals(UserXML.getUserId(AnswerListActivity.this)))
            tvAmend.setVisibility(View.VISIBLE);
        else
            tvAmend.setVisibility(View.GONE);

    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                AnswerVO answerVO = (AnswerVO) adapter.getAllData().get(position);
                GotoUtil.gotoActivity(AnswerListActivity.this, AnswerDetailActivity.class, "answerId", answerVO.getId());
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_SHOW_DETAILS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_SHOW_DETAILS_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        break;
                    case MSG.MSG_DELETE_QUESTION_SUCCESS:
                        showToast("删除成功");
                        Intent intent = new Intent();
                        intent.putExtra("questionId", questionId);
                        setResult(RESULT_OK, intent);
                        finish();
                        break;
                    case MSG.MSG_DELETE_QUESTION_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        answerVOList = FastJsonUtil.getListBean(object.toString(), "body", "otherAnswers", AnswerVO.class);
        AnswerVO myAnswer = FastJsonUtil.getBean(object.toString(), "body", "myAnswer", AnswerVO.class);

        if (myAnswer != null) {
            answerVOList.add(0, myAnswer);
            linearLayout.setVisibility(View.GONE);
        }

        // 判断该问题是不是当前登录帐号发布的并且没有回答 如果是则显示删除
        if (answerVOList.size() <= 0 && technologyVO.getPerson().getUserAccId().equals(UserXML.getUserId(AnswerListActivity.this))) {
            tvDelete.setVisibility(View.VISIBLE);
        } else {
            tvDelete.setVisibility(View.GONE);
        }

        if (page == 1 && null != answerVOList && answerVOList.size() > 0) { // 刷新
            adapter.clear();
        }


        if (answerVOList != null) {
            if (answerVOList.size() < limit) {
                adapter.stopMore();
            }
        }

        adapter.addAll(answerVOList);

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessQandA.showDetails(this, questionId, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @Override
    public void onLoadMore() {
            page++;
            BusinessQandA.showDetails(this, questionId, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_ASK_LIST && resultCode == RESULT_ANSWER_QUESTION_CODE)
            onRefresh();
    }
}
